import React, { useState, useRef, forwardRef, useImperativeHandle } from 'react';
import styles from './index.less';

const Child = forwardRef((props, ref) => {
  const [status] = useState('success');
  const alertMsg = () => {
    alert('Child => Hello World!');
  };
  useImperativeHandle(ref, () => ({ alertMsg }));
  return (
    <div style={{ color: 'orange' }}>
      <h4>{props.title}</h4>
      <p>i am in child component =&gt; {status}</p>
    </div>
  );
});

export default function Parent() {
  const childRef = useRef();
  const handleClick = () => {
    childRef.current.alertMsg();
  };
  return (
    <div className={styles.container}>
      <h4>I am parent!!!</h4>
      <button type="button" onClick={handleClick}>
        trigger child alter
      </button>
      <Child ref={childRef} title="暴露子组件api" />
    </div>
  );
}

// export default class Parent extends React.Component {
//   constructor(props) {
//     super(props);
//     this.cref = createRef();
//     this.inputRef = createRef();
//   }
//   handleClick = () => {
//     this.cref.current.alertMsg();
//   };
//   componentDidMount() {
//     this.inputRef.current.focus();
//     this.inputRef.current.value = 1;
//   }

//   render() {
//     return (
//       <div className={styles.container}>
//         <h2>I am parent!!!</h2>
//         <button onClick={this.handleClick}>trigger child alter</button>
//         <input type="text" ref={this.inputRef} />
//         <Child ref={this.cref} title="暴露子组件api" />
//       </div>
//     );
//   }
// }
